package com.lfy.modules.safety.filters;

import cn.hutool.extra.spring.SpringUtil;
import com.lfy.modules.common.domain.BaseEnum;
import com.lfy.modules.common.domain.R;
import com.lfy.modules.safety.blankMenu.BlackMenuCache;
import com.lfy.modules.common.utils.RequestUtil;
import com.lfy.modules.safety.statistics.pv.PvCache;
import com.lfy.modules.safety.statistics.uv.UvCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
public class BlackFilter implements Filter {
    private static final ThreadPoolExecutor SECONDARY_THREAD_POOL;
    private static final String HEART_BEAT_URI = "/api/heart";
    static {
        SECONDARY_THREAD_POOL = SpringUtil.getBean("secondaryThreadPool");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String ip = RequestUtil.getIp();
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String uri = req.getRequestURI();
        if(!uri.startsWith(HEART_BEAT_URI)){
            //pv统计
            SECONDARY_THREAD_POOL.execute(()->{
                PvCache.put();
                if(!StringUtils.isBlank(ip)){
                    UvCache.put(ip);
                }

            });
        }
        boolean contains = BlackMenuCache.isContains(ip);
        if (contains) {
            R<Void> error = R.error(BaseEnum.BlackEnum.BLACK_HANDLER);
            RequestUtil.writeResponse(error, servletResponse);
        }else {

            filterChain.doFilter(servletRequest, servletResponse);
        }

    }
}
